<?php
/* An easy way to keep in track of external processes.
 * Ever wanted to execute a process in php, but you still wanted to have somewhat controll of the process ? Well.. This is a way of doing it.
 * @compability: Linux only. (Windows does not work).
 * @author: Peec
 */
class Process{
    public $pid;
    public $command;

    public function __construct($cl=false){
        if ($cl != false){
            $this->command = $cl;
            $this->runCom();
        }
    }
    private function runCom(){
        $command = 'nohup '.$this->command.' > /dev/null 2>&1 & echo $!';
  
        exec($command ,$op);
        $this->pid = (int)$op[0];
    }

    public function setPid($pid){
        $this->pid = $pid;
    }

    public function getPid(){
        return $this->pid;
    }

    public function status(){
        $command = 'ps -p '.$this->pid;
        exec($command,$op);
        if (!isset($op[1]))return false;
        else return true;
    }

    public function start(){
        if ($this->command != '')$this->runCom();
        else return true;
    }

    public function stop(){
        $command = 'kill -9 '.$this->pid;
        exec($command);
        if ($this->status() == false)return true;
        else return false;
    }
    
    public function statusByPid( $pid ){
        $command = 'ps -p '.$pid;
        exec($command,$op);
        if (!isset($op[1]))return false;
        else return true;
    }
    
    public function stopByPid( $pid ){
        $command = 'kill -9 '.$pid;
        exec($command);
        if ($this->statusByPid( $pid ) == false)return true;
        else return false;
    }
    
    
    public function check_process_running( $key )
    {
       
        $key = escapeshellarg ( $key );  
        $cmd = 'ps aux|grep  '.$key.'|wc -l';
    
        $ret = shell_exec  ( $cmd );  
          
        if( is_null($ret) ) 
        {
            return false; 
        } 
        if(  intval( $ret ) >2  ){
            return true;
        } 
        return false;
         
    }
}
?> 